<?php
class nav extends Admin {

    private $name = "导航";

    public function index( $c, $a ) {
        $result = unserialize( $this->setting[ 'nav' ] );
        include $this->display( $c );
    }

    public function add( $c, $a ) {
        $sort = $this->get_sort_page();
        include $this->display( $c );
    }

    public function save() {
        $title = R( 'title' );
        foreach ( $_POST as $key => $val ) {
            $rows[ $title ][ $key ] = htmlspecialchars( trim( $val ) );
        }
        $rows[ $title ][ 'target' ] = isset( $_POST[ 'target' ] ) ? 1 : 0;

        if ( $old = unserialize( $this->setting[ 'nav' ] ) ) {
            $rows = array_merge( $old, $rows );
        }
        array_unique( $rows );
        $this->save_setting( $rows );
        $this->success( '添加导航成功!' );
    }

    public function del() {
        if ( !$title = R( 'id' ) ) {
            $this->error();
        }
        $arr = unserialize( $this->setting[ 'nav' ] );
        unset( $arr[ $title ] );
        $this->save_setting( $arr );
        $this->success( '删除导航成功!' );
    }

    public function order() {
        $nav = unserialize( $this->setting[ 'nav' ] );
        foreach ( $_POST[ 'oid' ] as $k => $v ) {
            if ( isset( $nav[ $k ] ) ) {
                $nav[ $k ][ 'oid' ] = $v;
            }
        }
        $this->save_setting( $nav );
        $this->success( '更新导航排序成功!' );
    }

    private function save_setting( $arr ) {
        $rows = arraySortByKey( $arr, 'oid' );
        $val = serialize( $rows );

        $sql = "REPLACE INTO " . $this->model->t( 'setting' ) . " VALUES ('nav', '{$val}')";
        $this->model->runSql( $sql );
        $this->model->Cache()->update( 'setting' );

        unset( $rows );
        unset( $arr );
        return true;
    }
}